<?php
namespace daswork;

// use daswork\Connect;
use mysqli;
use daswork\lib\Config;

class Model
{
    private $mydb;
    protected $tablename;

    public function __construct()
    {
        // $content = new Connect();  后期这得改成多次model 用一个连接
        $db = Config::get('db');
        $mydb = new mysqli($db['host'], $db['username'], $db['pwd'], $db['dbname']);
        if ($mydb->connect_error) {
            throw new \Exception('Connect Error (' . $mydb->connect_errno . ') '. $mydb->connect_error);
        } else {
            // echo "Opened database successfully\n";
            $this->connect = $mydb;
        }
    }

    /**
     * 执行sql
     * @param string $sql
     * @return mixd $res
     */
    public function query($sql)
    {
        $res = $this->mydb->query($sql);
        return $res;
    }
    
    public function lastInsertRowID()
    {
        $res = $this->mydb->insert_id;
        return $res;
    }

    public function lastErrorMsg()
    {
        return "Errorcode: %d\n" . $this->mydb->errno . $this->mydb->error;
    }

    /**
     * 查询数组列表
     */
    public function select($sql)
    {
        $result = $this->mydb->query($sql);
        $data = array();

        while ($arr = $result->fetch_assoc()) {
            $data[] = $arr;
        }
        return $data;
    }

    /**
     * 查询一条
     */
    public function getOneById($id, $tablename = '')
    {
        $tablename = $tablename ? $tablename : $this->tablename;
        $sql = "SELECT * FROM `$tablename` WHERE `id`=$id;";
        $result = $this->mydb->query($sql);

        $data = $result->fetch_assoc();
        // var_dump($data);
        return $data;
    }

    /**
     * 列表结果集
     */
    public function dataList($where = '')
    {
        $sql = "select * from $this->tablename $where;";
        return $this->select($sql);
    }

    /**
     * 分页结果集
     */
    public function pageList($where, $page = 1, $limit = 10)
    {
        $res = $this->query("select count(*) as total from $this->tablename $where;"); 
        $data = $res->fetch_assoc();
        
        $offset = ($page - 1) * $limit;
        $sql = "select * from $this->tablename $where limit $offset, $limit;";
        $list = $this->select($sql);
        $data['list'] = $list;
        $data['page'] = $page;
        $data['limit'] = $limit;
        
        return $data;
    }

    /**
     * save
     */
    public function save($data)
    {
        $columns = "";
        $values = "";
        foreach ($data as $key => $value) {
            $columns .=  "`" . $key . "`,";
            $values .=  "'" . $value . "',";
        }
        $columns = rtrim($columns, ',');
        $values = rtrim($values, ',');
        $sql = "INSERT INTO `$this->tablename`(" . $columns . ") VALUES(". $values . ");";
        // echo $sql;
        return $this->query($sql);
    }
    
    /**
     * updateById
     */
    public function updateById($data)
    {
        $id = $data['id'];
        unset($data['id']);
        $columns = "";
        foreach ($data as $key => $value) {
            $columns .= "`" . $key . "`='" . $value ."',";
        }
        $columns = rtrim($columns, ',');
        $sql = "UPDATE `$this->tablename` SET $columns WHERE `id`=$id";
        return $this->query($sql);
    }

    /**
     * deleteByIds
     */
    public function deleteById($id)
    {
        $sql = "DELETE FROM `$this->tablename` WHERE `id` IN(";
        if (is_array($id)) {
            for ($i=0; $i < count($id); $i++) {
                $sql .= $id[$i] . ',';
            }
            $sql = rtrim($sql, ',');
            $sql .= ");";
        } else {
            $sql = "DELETE FROM `$this->tablename` WHERE `id`=$id;";
        }
        return $this->query($sql);
    }

    public function __destruct()
    {
        $this->mydb->close();
    }
}
